// @author: caoshi
// @date: 2021-06-06 09:52
package main

import (
	"demo09_captcha/captcha"
	"demo09_captcha/model"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

const SessionId = "SESSION_ID"

var router = gin.Default()

// 初始化验证码
func InitCaptcha(c *gin.Context) {
	captchaId, b64s, _ := captcha.GenerateCaptcha(captcha.String)
	fmt.Println("生成的验证码 ", b64s)
	// 获取session, 并存储生成的验证码Id
	session := sessions.Default(c)
	session.Set(SessionId, captchaId)
	_ = session.Save()
	c.String(http.StatusOK, b64s)
}

// 用户登录
func Login(c *gin.Context) {
	var userJson model.Login
	err := c.ShouldBindJSON(&userJson)
	if err != nil {
		fmt.Println("获取参数失败")
	}
	session := sessions.Default(c)
	sessionValue := session.Get(SessionId)
	fmt.Println(">>>>>>>>>>>> session中存储的captchaId ", sessionValue)
	fmt.Println(">>>>>>>>>>> 用户输入的登录信息 ", userJson)
	capId := fmt.Sprintf("%v", sessionValue)
	pass := captcha.VerifyCaptcha(capId, userJson.Vcode)

	if strings.Compare(userJson.Username, "zs") == 0 &&
		strings.Compare(userJson.Password, "123") == 0 {

		if pass {
			fmt.Println("验证码输入正确")
		} else {
			fmt.Println("验证码输入错误")
		}

	}

}

func main() {
	// 1. 初始化session
	store := cookie.NewStore([]byte("secret11111"))
	router.Use(sessions.Sessions("mysession", store))

	router.GET("vcode", InitCaptcha)
	router.POST("login", Login)

	_ = router.Run(":8090")
}
